<template>
  <div class="product-list-container">
    <!-- 顶部导航栏 -->
    <div class="header-nav">
      <!-- 左侧搜索框 -->
      <div class="search-container">
        <el-input
            v-model="searchKeyword"
            placeholder="搜索商品"
            class="search-input"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="handleSearch" class="search-button">搜索</el-button>
      </div>
      <!-- 左侧分类选择 -->
      <div class="category-selector">
        <el-select v-model="selectedCategory" placeholder="商品分类" class="category-select">
          <el-option label="全部" value=""></el-option>
          <el-option v-for="category in categories" :key="category" :label="category" :value="category"></el-option>
        </el-select>
      </div>
    </div>

    <!-- 商品列表 -->
    <el-row :gutter="20" v-if="!showDetail">
      <el-col v-for="product in products" :key="product.id" :span="6">
        <div class="product-card">
          <el-card :body-style="{ padding: '0px' }">
            <img :src="product.imageUrl" class="product-image" @click="showProductDetail(product)" />
            <div class="product-info">
              <h3 class="product-name">{{ product.productName }}</h3>
              <p class="product-price">￥{{ product.price.toFixed(2) }}</p>
              <el-input-number
                  v-model="product.quantity"
                  :min="1"
                  :max="10"
                  label="数量"
                  size="small"
              ></el-input-number>
              <el-button
                  type="primary"
                  size="small"
                  @click="addToHiddenCart(product)"
              >
                加入隐藏购物车
              </el-button>
            </div>
          </el-card>
        </div>
      </el-col>
    </el-row>

    <!-- 商品详情 -->
    <div class="product-detail-container" v-else>
      <img :src="selectedProduct.imageUrl" class="product-detail-image" />
      <h2 class="product-name">{{ selectedProduct.productName }}</h2>
      <p class="product-price">￥{{ selectedProduct.price.toFixed(2) }}</p>
      <p class="product-description">{{ selectedProduct.description }}</p>
      <p class="product-preparation-time">制作时间：{{ selectedProduct.preparationTime }} 分钟</p>
      <el-input-number
          v-model="selectedProduct.quantity"
          :min="1"
          :max="10"
          label="数量"
          size="small"
      ></el-input-number>
      <el-button
          type="primary"
          size="small"
          @click="addToHiddenCart(selectedProduct)"
      >
        加入隐藏购物车
      </el-button>
      <el-button
          type="default"
          size="small"
          @click="hideProductDetail"
      >
        返回
      </el-button>
    </div>

    <!-- 分页 -->
    <div class="pagination-container" v-if="!showDetail">
      <el-pagination
          background
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[12, 24, 36, 48]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          class="pagination"
      />
    </div>

    <!-- 显示/隐藏购物车栏按钮 -->
    <div class="cart-toggle-button" v-if="!showDetail">
      <el-button type="primary" @click="toggleCartVisibility">{{ showCart ? '隐藏购物车' : '显示购物车' }}</el-button>
    </div>

    <!-- 隐藏的购物车栏 -->
    <div class="hidden-cart-container" v-if="showCart">
      <h2>隐藏购物车</h2>
      <div v-for="cartItem in hiddenCart" :key="cartItem.product.id" class="cart-item">
        <img :src="cartItem.product.imageUrl" class="cart-item-image" />
        <div class="cart-item-info">
          <h3 class="cart-item-name">{{ cartItem.product.productName }}</h3>
          <p class="cart-item-price">￥{{ cartItem.product.price.toFixed(2) }}</p>
          <p class="cart-item-quantity">数量: {{ cartItem.quantity }}</p>
          <el-button
              type="danger"
              size="small"
              @click="removeFromHiddenCart(cartItem)"
          >
            移除
          </el-button>
        </div>
      </div>
      <el-button
          type="success"
          size="small"
          @click="addToCartBatchFromHiddenCart"
      >
        批量加入购物车
      </el-button>
      <!-- 新增生成订单按钮 -->
      <el-button
          type="primary"
          size="small"
          @click="createOrder"
      >
        生成订单
      </el-button>
      <!-- 新增支付方式选择 -->
      <el-select v-model="selectedPaymentMethod" placeholder="请选择支付方式">
        <el-option label="现金支付" value="现金支付"></el-option>
        <el-option label="扫码支付" value="扫码支付"></el-option>
      </el-select>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import http from '@/axios/http';
import { Search } from '@element-plus/icons-vue';

const products = ref([]);
const pageNum = ref(1);
const pageSize = ref(12);
const total = ref(0);
const selectedCategory = ref(''); // 用于存储选中的商品分类
const categories = ref([]); // 存储所有商品分类
const showDetail = ref(false); // 控制是否显示商品详情
const selectedProduct = ref({}); // 存储当前选中的商品
const showCart = ref(false); // 控制是否显示隐藏购物车栏
const hiddenCart = ref([]); // 存储隐藏购物车栏中的商品
const selectedPaymentMethod = ref(''); // 存储选中的支付方式
const searchKeyword = ref(''); // 存储搜索关键词

const createOrder = () => {
  const cartItems = hiddenCart.value;
  if (cartItems.length === 0) {
    alert('请选择要生成订单的商品');
    return;
  }

  // 检查是否选择了支付方式
  if (!selectedPaymentMethod.value) {
    alert('请选择支付方式');
    return;
  }

  // 计算订单总金额
  let totalAmount = 0;
  const orderItems = cartItems.map(item => {
    const itemTotal = item.product.price * item.quantity;
    totalAmount += itemTotal;
    return {
      productId: item.product.id,
      quantity: item.quantity,
      price: item.product.price
    };
  });

  // 确保 totalAmount 不为 NaN 或 <= 0
  if (isNaN(totalAmount) || totalAmount <= 0) {
    alert('订单总金额计算错误');
    return;
  }

  // 获取系统当前时间
  const orderTime = new Date().toISOString().slice(0, 19).replace('T', ' ');

  // 构造订单数据
  const orderData = {
    userId: 1, // 假设当前用户 ID 是 1
    orderStatus: '制作中', // 订单状态
    totalAmount: totalAmount, // 确保 totalAmount 是一个数字
    paymentMethod: selectedPaymentMethod.value, // 添加支付方式
    orderTime: orderTime, // 添加订单时间
    orderItems: orderItems
  };

  // 调用后端接口生成订单
  http.post('/glsb/createOrder', orderData)
      .then(response => {
        if (response.data.result === 'success') {
          alert('订单生成成功');
          hiddenCart.value = []; // 清空隐藏购物车栏
          selectedPaymentMethod.value = ''; // 清空支付方式选择
        } else {
          alert(response.data.error);
        }
      })
      .catch(error => {
        console.error('生成订单失败:', error);
      });
};

const fetchCategories = async () => {
  try {
    const response = await http.get('/glsb/getAllCategories');
    if (response.data.result === 'success') {
      categories.value = response.data.data;
    } else {
      alert(response.data.error);
    }
  } catch (error) {
    console.error('获取商品分类出错:', error);
  }
};

const fetchProducts = async () => {
  try {
    let response;
    if (searchKeyword.value) {
      // 如果有搜索关键词，调用 get_product_by 方法
      const requestData = {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        productName: searchKeyword.value
      };
      response = await http.post('/glsb/get_product_by', requestData);
    } else {
      // 如果没有搜索关键词，调用 get_all_products 方法
      const requestData = {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        productCategory: selectedCategory.value
      };
      response = await http.post('/glsb/get_all_products', requestData);
    }

    if (response.data.result === 'success') {
      const productList = response.data.data.list || [];
      products.value = productList.map(product => {
        // 为无效的图片链接提供默认图片
        return {
          ...product,
          imageUrl: product.imageUrl === '/' ? 'https://via.placeholder.com/200x200' : product.imageUrl
        };
      });
      total.value = response.data.data.total || 0;
    } else {
      alert(response.data.error);
    }
  } catch (error) {
    console.error('获取商品信息出错:', error);
  }
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchProducts();
};

const handlePageChange = (newPage) => {
  pageNum.value = newPage;
  fetchProducts();
};

const handleSearch = () => {
  // 搜索时重置分页
  pageNum.value = 1;
  fetchProducts();
};

const addToHiddenCart = (product) => {
  const existingItem = hiddenCart.value.find(item => item.product.id === product.id);
  if (existingItem) {
    existingItem.quantity += product.quantity;
  } else {
    hiddenCart.value.push({
      product: {
        ...product
      },
      quantity: product.quantity
    });
  }
};

const removeFromHiddenCart = (cartItem) => {
  hiddenCart.value = hiddenCart.value.filter(item => item.product.id !== cartItem.product.id);
};

const addToCart = (product) => {
  http.post('/glsb/addToCart', {
    userId: 1, // 假设当前用户 ID 是 1
    productId: product.id,
    quantity: product.quantity
  }).then(response => {
    if (response.data.result === 'success') {
      alert('商品已加入购物车');
    } else {
      alert(response.data.error);
    }
  }).catch(error => {
    console.error('加入购物车失败:', error);
  });
};

const addToCartBatchFromHiddenCart = () => {
  const cartItems = hiddenCart.value.map(item => ({
    userId: 1, // 假设当前用户 ID 是 1
    productId: item.product.id,
    quantity: item.quantity
  }));

  if (cartItems.length === 0) {
    alert('请选择要加入购物车的商品');
    return;
  }

  http.post('/glsb/addToCartBatch', cartItems)
      .then(response => {
        if (response.data.result === 'success') {
          alert('批量添加到购物车成功');
          hiddenCart.value = []; // 清空隐藏购物车栏
        } else {
          alert(response.data.error);
        }
      })
      .catch(error => {
        console.error('批量添加到购物车失败:', error);
      });
};

const showProductDetail = (product) => {
  selectedProduct.value = product;
  showDetail.value = true;
};

const hideProductDetail = () => {
  showDetail.value = false;
};

const toggleCartVisibility = () => {
  showCart.value = !showCart.value;
};

watch(selectedCategory, () => {
  console.log('分类发生变化，新的分类:', selectedCategory.value);
  pageNum.value = 1; // 切换分类时重置页码为 1
  fetchProducts();
});

onMounted(async () => {
  await fetchCategories();
  fetchProducts();
});
</script>

<style scoped>
.product-list-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
  font-family: Arial, sans-serif;
}

.header-nav {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-bottom: 20px;
}

.category-selector {
  width: 200px; /* 调整分类选择框宽度 */
  margin-top: 10px;
}

.category-select {
  width: 100%; /* 使选择框填满父容器 */
}

.search-container {
  display: flex;
  align-items: center;
  width: 300px; /* 调整搜索框和按钮的总宽度 */
}

.search-input {
  flex: 1; /* 让输入框占据剩余空间 */
}

.search-button {
  margin-left: 10px; /* 在按钮和输入框之间添加一些间距 */
}

.product-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.3s ease;
}

.product-card:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.product-image:hover {
  transform: scale(1.05);
}

.product-info {
  padding: 10px;
  background-color: #fff;
}

.product-name {
  font-size: 16px;
  margin: 0 0 5px;
  color: #333;
}

.product-price {
  font-size: 14px;
  color: #ff5722;
  margin: 0 0 10px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.product-detail-container {
  padding: 20px;
  background-color: #fff;
  text-align: center;
  margin-top: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.product-detail-image {
  width: 500px; /* 调整照片宽度 */
  height: 500px; /* 调整照片高度 */
  object-fit: cover;
  margin-bottom: 20px;
  border-radius: 8px;
}

.product-detail-container .product-name {
  font-size: 24px;
  margin-bottom: 10px;
  color: #333;
}

.product-detail-container .product-price {
  font-size: 18px;
  color: #ff5722;
  margin-bottom: 10px;
}

.product-detail-container .product-description {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.product-detail-container .product-preparation-time {
  font-size: 14px;
  color: #666;
  margin-bottom: 20px;
}

.cart-toggle-button {
  text-align: center;
  margin-top: 20px;
}

.hidden-cart-container {
  padding: 20px;
  background-color: #fff;
  margin-top: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.cart-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  border-bottom: 1px solid #ddd;
  padding-bottom: 10px;
}

.cart-item:last-child {
  border-bottom: none;
}

.cart-item-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  margin-right: 10px;
  border-radius: 8px;
}

.cart-item-info {
  flex: 1;
}

.cart-item-name {
  font-size: 16px;
  margin: 0 0 5px;
  color: #333;
}

.cart-item-price {
  font-size: 14px;
  color: #ff5722;
  margin: 0 0 5px;
}

.cart-item-quantity {
  font-size: 14px;
  color: #666;
  margin: 0;
}
</style>